package cn.edu.zafu.bigdata.LiJuan.ch11;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class UDPServer {
    public static void main(String[] args) {
        int port = 12345; // 服务端监听的端口
        try (DatagramSocket socket = new DatagramSocket(port)) {
            System.out.println("时钟同步服务端启动，端口：" + port);

            while (true) {
                byte[] receiveData = new byte[1024];
                byte[] sendData = new byte[1024];

                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                socket.receive(receivePacket);

                String receiveMessage = new String(receivePacket.getData()).trim();
                System.out.println("收到客户端请求：" + receiveMessage);

                String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                System.out.println("服务端当前时间：" + currentTime);

                sendData = currentTime.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort());
                socket.send(sendPacket);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}